<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            width: 150px;
            height: 100px;
            background-color: springgreen;

            position: relative;
            top:  0;
            left: 0;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <script>
        var box = document.querySelector(".box")
        //每一次移动的步子
        var stepx = 5;
        //总共移动的距离
        var sumx = 0;

         //每一次移动的步子
         var stepy = 5;
        //总共移动的距离
        var sumy = 0;
        setInterval(function(e){
            sumx += stepx;
            //让盒子跟着移动
            box.style.left = sumx + 'px';
            //临界值的判断
            if(box.offsetLeft >= document.documentElement.clientWidth - box.offsetWidth || box.offsetLeft<=0){
                //表述马上就要出去了
                stepx = -stepx;
            }

            //总距离需要累加stepx
            sumy += stepy;
            //让盒子跟着移动
            box.style.top = sumy + 'px';
            //临界值的判断
            if(box.offsetTop >= document.documentElement.clientHeight - box.offsetHeight || box.offsetTop<=0){
                //表述马上就要出去了
                stepy = -stepy;
            }
        },16)
    </script>
</body>
</html>